<!--
*@Author: QWP
*@Description: 收入合同编辑
*@Date: 2024-07-08 17:04:38
-->
<template>
  <u-dialog v-bind="$attrs"
    :confirmLoading="formLoading"
    :hideBtns="isCheck ? ['submit'] : []"
    @submit="submit"
    @close="dialogClose">
    <a-layout class="f-h-100">
      <a-layout-content class="s-bg-white"
        style="overflow-y: auto; overflow-x: hidden;">
        <a-space  direction="vertical"  class="f-w-100">
          <u-busi-card title="基本信息"
            :bordered="false">
            <u-form :elements="formEls"
              :model="form"
              :gutter="0"
              :disabled="isCheck"
              :hideRequiredMark="isCheck"
              :loading="formLoading"
              ref="formRef">
              <template #aname>
                <SelAdd v-model:value="form.aname" v-bind:options="companyData" 
                  @success="selAddSuccess()"/>
              </template>
              <template #bname>
                <SelAdd v-model:value="form.bname" v-bind:options="companyData"
                  @success="selAddSuccess()"/>
              </template>
            </u-form>
          </u-busi-card>
          <u-busi-card title="付款约定"
            :bordered="false">
            <u-edit-table :columns="detialCols"
              :check="isCheck"
              :data="detialTabData"
              :loading="formLoading"
              :scroll="{ y: 300 }">
            </u-edit-table>
          </u-busi-card>
        </a-space>
      </a-layout-content>
    </a-layout>
  </u-dialog>
</template>

<script lang='ts' setup>
import { ref, reactive, computed, onMounted, h, watch, useAttrs } from 'vue' 
import { useRoute, useRouter } from 'vue-router'
import { useLoginStore, useBaseStore } from '@/store'
import { storeToRefs } from 'pinia'
import { _IFormEl, _IExtra } from '@/src/components/common/form/interface';
import { FormInstance, FormItemProps } from 'ant-design-vue';
import { _IColumnProps } from '@/components/common/tableEdit/interface.ts'
import { formatAmt } from '@/util/format.ts'
import { numberC, messageC, isValue } from '@/util/common'
import { takeC, divideC, addC } from '@/util/computePtrcision.ts'
import SelAdd from './SelAdd.vue'
import * as contractApi from '@/service/administration/contract'
import * as contractCoopApi from '@/service/administration/contractCooperate'
import dayjs from 'dayjs';

const props = defineProps<{
  keyid?: string,
}>()

const attrs = useAttrs()
const route = useRoute()
const emits = defineEmits(['success'])

const { userInfo } = storeToRefs(useLoginStore())
const { deptData } = storeToRefs(useBaseStore())

const isCheck = computed(() => route.params.pType == 3)

// 合作的甲乙双方公司
const companyData = ref<any[]>([])

const formLoading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref({})
const formItemProps: FormItemProps & _IExtra = {
  labelWidth: '90px',
  colon: false
}
const formEls: Array<_IFormEl> = reactive([
  { label: '合同编号', key: 'contractcode', col: { span: 8,}, element: 'input', 
    formItemProps: { ...formItemProps, required: true } 
  },
  { label: '合同名称', key: 'contractname', col: { span: 8,}, element: 'input', 
    formItemProps: { ...formItemProps, required: true } 
  },
  { label: '合同金额', key: 'contractamount', col: { span: 8,}, element: 'money', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      addonAfter: '元',
      onChange: () => calcRateAmt()
    }
  },
  { label: '创建部门', key: 'fkdeptid', col: { span: 8 }, element: 'select', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: { options: deptData.value } 
  },
  { label: '创建人', key: 'reusername', col: { span: 8 }, element: 'input', 
    formItemProps: { ...formItemProps, },
    componentProps: { disabled: true } 
  },
  { label: '甲方名称', key: 'aname', col: { span: 8 }, element: 'slot', 
    formItemProps: { ...formItemProps, required: true,
     rules: { trigger: 'change' ,
        validator: async (_rule, value: string) => {
          if (value === '') {
            return Promise.reject("甲方名称不能为空！");
          } else if (value === form.value.bname) {
            return Promise.reject("甲乙双方名称不能相同!");
          } else {
            return Promise.resolve();
          }
        },  
      }  
    } ,
  },
  { label: '乙方名称', key: 'bname', col: { span: 8 }, element: 'slot', 
    formItemProps: { ...formItemProps, required: true,
      rules: { trigger: 'change' ,
        validator: async (_rule, value: string) => {
          if (value === '') {
            return Promise.reject("乙方名称不能为空！");
          } else if (value === form.value.aname) {
            return Promise.reject("甲乙双方名称不能相同!");
          } else {
            return Promise.resolve();
          }
        },  
      }  
    },
  },
  { label: '签定时间', key: 'contractdate', col: { span: 8 }, element: 'datepicker', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      disabledDate: (current?: any) => {
        return current && current > dayjs().endOf('day')
      }
    } 
  },
  { label: '备注', key: 'remark', col: { span: 24 }, element: 'textarea', 
    formItemProps: { ...formItemProps,} 
  },
  { label: '合同附件', key: 'appendixSaveVOList', col: { span: 24,}, element: 'file', 
    formItemProps: { ...formItemProps, required: true },
    componentProps: {
      fileParams: { biztype: '1', bucket: 'pur', }
    }
  }
])

watch(() => form.value.appendixSaveVOList, (nval, oval) => {
  if(nval) {
    formRef.value.form.clearValidate(['appendixSaveVOList'])
  }
}, { deep: true })

// 付款约定
const detialTabData = ref<any[]>([]); 
const detialCols: Array<_IColumnProps> = [
  { title: '*付款批次', dataIndex: 'batchnum', width: 100, align: 'center'},
  { title: '*付款比例(%)', dataIndex: 'payrate', width: 170, element: 'number',
    componentProps: {
      controls: false, precision: 2, max: 100
    }
  },
  { title: '*付款金额', dataIndex: 'payamount', width: 170, 
    customRender: ({ text }) => {
      return formatAmt(numberC(text))
    }
  },
  { title: '*付款时间', dataIndex: 'paydate', width: 170, element: 'datepicker' ,
    componentProps: {
      format: 'YYYY-MM-DD', valueFormat: 'YYYY-MM-DD',
    }
  },
  { title: '备注', dataIndex: 'remark', minWidth: 150, element: 'input' },
]; 

// 初始化表单数据
const initFormValue = () => {
  form.value.fkuserid= userInfo.value["userId"];
  form.value.reusername= userInfo.value["name"];
  form.value.fkdeptid= userInfo.value["deptId"];
  form.value.redeptname= userInfo.value["deptName"];
  form.value.fkunitsid= userInfo.value["unitId"];
  form.value.unitName= userInfo.value["unitName"];

  form.value.contracttype= computed(() => route.params.pType);
}

// 确认提交
const submit = async () => {
  try {
    await formRef.value.form.validate()
  } catch (error) {
    messageC("请先将表单必填项填写完毕！");
    return
  }

  // 验证付款约定
  if(submitVeryfy() == false) return

  formLoading.value = true;
  try {
    const url = form.value.keyid ? "update" : "add";
    const data = await contractApi[url]({ ...form.value, purTContractdetails: detialTabData.value });
    if (data.code == 0) {
      messageC(data.msg, "success");
      emits("success");
      dialogClose()
    } else {
      alertC(res.msg, "warning");
    }
  } catch (error) {}
  formLoading.value = false;
}

// 保存验证
const submitVeryfy = (): boolean => {

  if(detialTabData.value.length == 0) {
    messageC("请先将付款约定填写完毕!");
    return false
  }

  // 付款批次未必录项
  let isNoBatchNam = detialTabData.value.some(i => !isValue(i['batchnum']));
  let isNoPaydate = detialTabData.value.some(i => !isValue(i['paydate']));
  if(isNoBatchNam || isNoPaydate) {
    messageC("请将付款约定列表中的【付款批次、付款时间】字段填写完毕！");
    return false
  }

  // 付款比例应达到100%
  let rateEqs100 = [0, ...detialTabData.value.map(i => numberC(i.payrate))].reduce((a, b) => addC(a, b))
  if(rateEqs100 != 100) {
    messageC("付款约定比例不等于100%,不能保存!");
    return false
  }

  // 付款时间应晚于签订时间
  let payDatAfterSignDate = detialTabData.value.some(i => dayjs(i.paydate).isBefore(dayjs(form.value.contractdate)))
  if(payDatAfterSignDate) {
    messageC("付款约定列表中的付款时间应晚于合同签订时间【"+ form.value.contractdate +"】!");
    return false
  }

  return true
}

// 计算比例对应的金额
const calcRateAmt = () =>  {
  detialTabData.value.forEach((item, index) => {
    item.batchnum = index + 1;
    item.payamount = divideC(
      takeC( numberC(item['payrate']), numberC(form.value['contractamount']) ),
      100
    );
  })
}

const selAddSuccess = () => {
  try {
    formRef.value.form.validateFields(['aname', 'bname'])
    formRef.value.form.clearValidate(['aname', 'bname'])
  } catch (error) {}
}

watch(() => detialTabData.value, (nval, oval) => {
  calcRateAmt()
}, { deep: true })

// 获取甲乙合作公司
const getCompany = async (isLoading?: boolean = true) => {
  formLoading.value = true;
  try {
    const res = await contractCoopApi.page({
      model: { keywords: null, },
      current: 1,
      size: 200000,
    })
    if(res.code == 0) {
      companyData.value = res.data.records
    }
  } catch (error) {}
  formLoading.value = false;
}

// 回显数据
const echoInfo = async() => {
  formLoading.value = true;
  try {
    const res = await contractApi.query(props.keyid);
    if(res.code == 0) {
      form.value = res.data || {};

      detialTabData.value = form.value['purTContractdetails'] || [];
    }
  } catch (error) {}
  formLoading.value = false;
}

// 弹窗关闭
const dialogClose = () => {
  formLoading.value = false;
  form.value = {};
  formRef.value.form.resetFields();
  detialTabData.value = []
}

watch(() => attrs.open, (nval, oval) => {
  if (nval == true) {
    initFormValue();
    getCompany();
    if (props.keyid != "") {
      echoInfo();
    }
  }
})
</script>

<style lang='scss' >
</style>